#include <Windows.h>
#include <tchar.h>
#include "resource.h"
#define IDT_SIMULATE 0x7000

void RunNotepad()
{
	STARTUPINFO si = {0};
	si.cb	= sizeof(si);
	PROCESS_INFORMATION pi = {0};
	TCHAR szPath[] = _T("notepad.exe");
	CreateProcess(NULL, szPath, NULL, NULL, FALSE, 0, 0, NULL, &si, &pi);
	CloseHandle(pi.hProcess);
	CloseHandle(pi.hThread);

	return;
}

int CALLBACK DlgProc(HWND hDlg, UINT nMsg, WPARAM wParam, LPARAM lParam)
{
	static bool bStart = false;
	switch (nMsg)
	{
		case WM_INITDIALOG:
		{
			SetWindowText(hDlg, _T("Demo0102"));

			UINT nWidth		= GetSystemMetrics(SM_CXSCREEN);
			UINT nHeight	= GetSystemMetrics(SM_CYSCREEN);
			RECT rtClient;
			GetClientRect(hDlg, &rtClient);
			SetWindowPos(hDlg, NULL, (nWidth - (rtClient.right - rtClient.left)) / 2, (nHeight - (rtClient.bottom - rtClient.top)) / 2, 0, 0, SWP_NOSIZE);

			break;
		}
		case WM_COMMAND:
		{
			switch (LOWORD(wParam))
			{
				case IDC_BTNSTART:
				{
					if (!bStart)
					{
						SetDlgItemText(hDlg, IDC_BTNSTART, _T("Stop"));
						SetTimer(hDlg, IDT_SIMULATE, 3000, NULL);
						bStart = true;
					} else {
						SetDlgItemText(hDlg, IDC_BTNSTART, _T("Start"));
						KillTimer(hDlg, IDT_SIMULATE);
						bStart = false;
					}
					break;
				}
			}
			break;
		}
		case WM_TIMER:
		{
			if (wParam == IDT_SIMULATE)
			{
				HWND hNotePad = FindWindow(_T("Notepad"), NULL);
				if (NULL == hNotePad)
				{
					RunNotepad();
					Sleep(500);
				}

				if (NULL != hNotePad)
				{
					SetForegroundWindow(hNotePad);

					RECT rtClient;
					GetWindowRect(hNotePad, &rtClient);
					UINT nSnWidth	= GetSystemMetrics(SM_CXSCREEN);
					UINT nSnHeight	= GetSystemMetrics(SM_CYSCREEN);

					long x = (rtClient.left + 100);// * 65535 /  nSnWidth;
					long y = (rtClient.top + 10);// * 65535  / nSnHeight;
					POINT pt;
					GetCursorPos(&pt);
					ShowCursor(false);
					SetCursorPos(x, y);
					mouse_event(MOUSEEVENTF_ABSOLUTE|MOUSEEVENTF_LEFTDOWN|MOUSEEVENTF_LEFTUP, x, y, NULL, NULL);
					mouse_event(MOUSEEVENTF_ABSOLUTE|MOUSEEVENTF_LEFTDOWN|MOUSEEVENTF_LEFTUP, x, y, NULL, NULL);
					SetCursorPos(pt.x, pt.y);
					ShowCursor(true);
				}
			}
			break;
		}
		case WM_CLOSE:
		{
			KillTimer(hDlg, IDT_SIMULATE);
			PostQuitMessage(0);
			break;

		}
	}

	return 0;
}

BOOL WINAPI _tWinMain(HINSTANCE hInstance, HINSTANCE hPreInstance, LPTSTR szCmdLine, int nShowCmd)
{
	DialogBox(hInstance, MAKEINTRESOURCE(IDD_DIALOG), NULL, DlgProc);

	return TRUE;
}